<template>
    <el-row>
        <el-col :span="24">
        <el-form :inline="true">
          <el-form-item><el-button size="small" type="primary" @click="exportExcel">导出</el-button></el-form-item>
          <el-form-item><el-button size="small" type="primary" @click="CreateOneFormPage">打印</el-button></el-form-item>

          <el-form-item>
            <el-input v-model="dataForm.key" size="small" placeholder="房间号"></el-input>
          </el-form-item>


          <el-form-item>
            <el-input v-model="dataForm.tdkey" size="small" placeholder="团队单位"></el-input>
          </el-form-item>


          <el-form-item>
            <el-select v-model="dataForm.leix" clearable placeholder="房间类型">
               <el-option
                 v-for="item in leixlist"
                 :key="item.id"
                 :label="item.name"
                 :value="item.id">
               </el-option>
             </el-select>
          </el-form-item>


          <el-form-item>
            <el-select v-model="dataForm.rzzt" clearable placeholder="入住状态">
               <el-option
                 v-for="item in ztlist"
                 :key="item.id"
                 :label="item.name"
                 :value="item.id">
               </el-option>
             </el-select>
          </el-form-item>


          <el-form-item>
            <el-select v-model="dataForm.rzlx" clearable placeholder="入住类型">
               <el-option
                 v-for="item in rzlxlist"
                 :key="item.id"
                 :label="item.name"
                 :value="item.id">
               </el-option>
             </el-select>
          </el-form-item>









          <el-form-item>
            <el-radio-group @change="getDataList()" v-model="dataForm.dayType" size="small">
              <!-- <el-radio-button label="全部"></el-radio-button> -->
              <el-radio-button label="1">自然日</el-radio-button>
              <el-radio-button label="2">营业日</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-radio-group @change="getDataList()" v-model="dataForm.selDateAdd" size="small">
              <!-- <el-radio-button label="全部"></el-radio-button> -->
              <el-radio-button label="1">今日</el-radio-button>
              <el-radio-button label="2">昨日</el-radio-button>
              <el-radio-button label="3">本周</el-radio-button>
              <el-radio-button label="4">其他</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="dataForm.selDateAdd == '4'">
              <el-date-picker
              v-if="dataForm.dayType=='2'"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  value-format="yyyy-MM-dd"
                   v-model="dataForm.datast"
                  @change="getDataList()"
                  end-placeholder="结束日期">
                </el-date-picker>


                  <el-date-picker
                  v-if="dataForm.dayType=='1'"
                      v-model="dataForm.datastime"
                      type="datetimerange"
                      range-separator="至"
                       value-format="yyyy-MM-dd HH:mm:ss"
                      start-placeholder="开始日期"
                       @change="getDataList()"
                      end-placeholder="结束日期">
                    </el-date-picker>

          <!--  <el-date-picker  size="small"   type="date" placeholder="开始日期"></el-date-picker>
            <el-date-picker v-if="dataForm.dayType=='2'" size="small" @change="getDataList()" v-model="dataForm.endDate" value-format="yyyy-MM-dd" type="date" placeholder="结束日期"></el-date-picker>
    -->     <!--   <el-date-picker  size="small" @change="getDataList()" v-model="dataForm.startDateTime" type="datetime" placeholder="开始日期"></el-date-picker>
            <el-date-picker v-if="dataForm.dayType=='1'" size="small" @change="getDataList()" v-model="dataForm.endDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束日期"></el-date-picker>
         --> </el-form-item>

          <el-popover
            placement="top"
            width="160"
            v-model="visible">
            <div style=" margin: 0">
                <!-- <template v-for="(item,key) in selectedColumn" >
                    <el-checkbox v-model="columns[key]" :key="key">{{key}}</el-checkbox>
                </template> -->
                <el-checkbox-group v-model="column" @change="columnChange">
                    <el-checkbox v-for="(item,index) in columns" :label="index" :key="index"> {{index}}</el-checkbox>
                </el-checkbox-group>
            </div>
            <el-button slot="reference" size="small" style="margin-top: 2px;float: right;">选择列</el-button>
            </el-popover>

            <el-form-item>
                <el-button @click="getDataList()" size="small">查询</el-button>
            </el-form-item>
        </el-form>
        </el-col>

        <el-col :span="24">
            <el-table
                :data="tableData"
                border
                show-summary
                :summary-method="tableSum"
                style="width: 100%"
                ref="table"
                id="tableData"
                >


                    <!-- private String floorRoomNum;
    private String userName;
    private String roomType;
    private String state;
    private Date startTime;
    private Date endTime;
    private Float roomPrice; -->
                <el-table-column
                fixed="left"
                prop="floorRoomNum"
                sortable
                label="房间"
                width="100"
                v-if="selectedColumn['房间']!=undefined"
                >
                </el-table-column>

                <el-table-column
                fixed="left"
                prop="userName"
                sortable
                label="姓名"
                width="100"
                v-if="selectedColumn['姓名']!=undefined"
                >
                </el-table-column>
                <el-table-column
                fixed="left"
                prop="cardNo"
                sortable
                label="会员卡号"
                width="100"
                v-if="selectedColumn['会员卡号']!=undefined"
                :show-overflow-tooltip="true"
                >
                </el-table-column>
                <el-table-column
                prop="agreement"
                fixed="left"
                label="团体单位"
                sortable
                width="100"
                v-if="selectedColumn['团体单位']!=undefined"
                >

                </el-table-column>
                <el-table-column
                prop="roomType"
                fixed="left"
                label="房间类型"
                sortable
                width="100"
                v-if="selectedColumn['房间类型']!=undefined"
                >
                </el-table-column>
                <el-table-column
                prop="checkinType"
                fixed="left"
                sortable
                label="入住类型"
                width="100"
                v-if="selectedColumn['入住类型']!=undefined"
                >
                <template slot-scope="scope">
                    {{checkTypes[scope.row.checkinType]}}
                </template>
                </el-table-column>
                <el-table-column
                fixed="left"
                prop="state"
                sortable
                label="状态"
                width="100"
                v-if="selectedColumn['状态']!=undefined"
                >
                </el-table-column>

                <el-table-column
                prop="startTime"
                sortable
                label="入住时间"
                width="200"
                v-if="selectedColumn['入住时间']!=undefined"
                >
                </el-table-column>
                <el-table-column
                prop="endTime"
                sortable
                label="预离时间"
                width="200"
                v-if="selectedColumn['预离时间']!=undefined"
                >
                </el-table-column>
                <el-table-column
                prop="housePrice"
                sortable
                label="标准房价"
                v-if="selectedColumn['标准房价']!=undefined"
                width="100"
                >

                </el-table-column>
                <el-table-column
                prop="roomPrice"
                label="房费"
                sortable
                width="100"
                v-if="selectedColumn['房费']!=undefined"
                >
                </el-table-column>

                <el-table-column
                prop="hc"
                sortable
                label="红冲"
                v-if="selectedColumn['红冲']!=undefined"
                >
                <template slot-scope="scope">
                    {{0-scope.row.hc}}
                </template>
                </el-table-column>
                <el-table-column
                prop="yhje"
                sortable
                label="优惠金额"
                v-if="selectedColumn['优惠金额']!=undefined"
                >
                <template slot-scope="scope">
                    {{0-scope.row.yhje}}
                </template>
                </el-table-column>



                <el-table-column sortable v-for="column in consumeColumn" :key="column.consumeId" :label="column.name" width="100" v-if="selectedColumn[column.name]!=undefined">
                    <template slot-scope="scope">
                        <span v-for="item in tableData[scope.$index].consumeInfo" :key="item.payTypeName" v-if="item.payTypeName==column.name">
                            {{item.paySum}}
                        </span>
                      <span v-if="tableData[scope.$index].consumeInfo.length==0">
                         0
                      </span>
                    </template>
                </el-table-column>
                <el-table-column
                sortable
                    label="费用合计"
                    v-if="selectedColumn['费用合计']!=undefined"
                >
                <template slot-scope="scope">
                    {{sum(scope.row.consumeInfo)-scope.row.hc+scope.row.roomPrice}}
                </template>

                </el-table-column>



                <el-table-column sortable v-for="column in paymentColumn" :key="column.consumeId" :label="column.name" width="100" v-if="selectedColumn[column.name]!=undefined">
                    <template slot-scope="scope">
                        <span v-for="item in tableData[scope.$index].payment" :key="item.paymentName" v-if="item.paymentName==column.name">
                            {{item.paymentSum==null||item.paymentSum==''?0:item.paymentSum}}
                        </span>
                      <span v-if="tableData[scope.$index].payment.length==0">
                         0
                      </span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="收款合计"
                    sortable
                    v-if="selectedColumn['收款合计']!=undefined"
                >
                <template slot-scope="scope">
                    {{paymentSum(scope.row.payment)}}
                </template>
                </el-table-column>

            </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        </el-col>
    </el-row>
</template>



<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import print from 'print-js'
import Moment from 'moment'
import $ from 'jquery'
export default {
    data() {
        return {
        loadColumn:false,
        dataForm: {
            startDate: '',
            endDate: '',
            startDataTime:'',
            endDateTime:'',
            selDateAdd: '1',
            key:'',
            dayType:'1',
            datast:[],
            datastime:[]
        },
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        checkColumn:{},
        visible:false,
        tableData: [],
        printFlag:false,
        leixlist:[],
        columns:{
            '房间':true,
            '姓名':true,
            '会员卡号':true,
            '团体单位':true,
            '房间类型':true,
            '入住类型':true,
            '状态':true,
            '入住时间':true,
            '预离时间':true,
            '标准房价':true,
            '房费':true,
            '红冲':true,
            '优惠金额':true,
            '费用合计':true,
            '收款合计':true
        },
        column:[
            '房间',
            '姓名',
            '会员卡号',
            '团体单位',
            '入住类型',
            '房间类型',
            '状态',
            '入住时间',
            '预离时间',
            '标准房价',
            '房费',
            '红冲',
            '优惠金额',
            '费用合计',
            '收款合计'
        ],
        consumeColumn:[],
        paymentColumn:[],
        rzlxlist:[
          {name:'全天房',id:'0' },
          {name:'时租房',id:'1' },
          {name:'自用房',id:'2' },
          {name:'免费房',id:'3' },
          {name:'长包房',id:'4' }
        ],
        ztlist:[
          {name:'正常入住',id:'1' },
          {name:'已结退房',id:'0' },
          {name:'未结离店',id:'2' },
          {name:'联房退房',id:'3' }
        ],

        consumeSum:0,
        paymentSums:0,
        selectedColumn:{
            '房间':true,
            '姓名':true,
            '会员卡号':true,
            '团体单位':true,
            '入住类型':true,
            '房间类型':true,
            '状态':true,
            '入住时间':true,
            '预离时间':true,
            '标准房价':true,
            '房费':true,
            '红冲':true,
              '优惠金额':true,
            '费用合计':true,
            '收款合计':true
        },
        seller:'',
        checkTypes:[
        '全天','时租','自用','免费'
        ]
}
    },
    methods:{
        getSellerAndUser() {
            this.$http({
            url: this.$http.adornUrl('/hotel/thotelfloorroomcheckinaccounting/getUserAndSeller'),
            method: 'get'
        }).then(({ data }) => {
            if (data && data.code === 0) {
                this.seller = data.sellerName
            console.log(data)
            } else {

            }
        })
        },
        getColumn() {
            this.$refs.table.$children.forEach(obj => {
                if (obj.label != undefined) { this.columns[obj.label] = true }
                this.column.push(obj.label)
            })
        },
        getleix() {
          this.$http({
              url: this.$http.adornUrl('/hotel/hotelroom/roomlist'),
              method: 'get',
              params: this.$http.adornParams({
              })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.leixlist = data.page;
          } else {
                  this.leixlist = [];

                  this.$message.error(data.msg);
              }
          });
        },
        getDataList() {
            console.log(this.dataForm)
            var startdate = '';
            var enddate = '';
               if (this.dataForm.dayType == '2') {
                startdate = this.dataForm.datast[0];
                 enddate = this.dataForm.datast[1];
               } else {
                 startdate = this.dataForm.datastime[0];
                  enddate = this.dataForm.datastime[1];
               }
            this.$http({
                url: this.$http.adornUrl('/hotel/thotelfloorroomcheckinpeople/businessDayReportFormList'),
                method: 'get',
                params: this.$http.adornParams({
                    page: this.pageIndex,
                    limit: this.pageSize,
                    key: this.dataForm.key,
                    leix:this.dataForm.leix,
                    rzzt:this.dataForm.rzzt,
                    rzlx:this.dataForm.rzlx,
                    tdkey:this.dataForm.tdkey,
                    rqlx:this.dataForm.dayType,
                    selDateAdd: this.dataForm.selDateAdd,
                    startDate:startdate,
                    endDate:enddate
                })
            }).then(({ data }) => {
                console.log("data",data)
                if (data && data.code === 0) {
                    this.tableData = data.page.list;
                    this.consumeColumn = data.consumeColumn
                    this.paymentColumn = data.paymentColumn
                    console.log(this.tableData,this.tableData.length)
                    this.totalPage = data.page.totalCount;

                    this.consumeColumn.forEach(item=>{
                        this.columns[item.name] = true
                        // for(var i=0;i<this.columns.length;i++){
                        //   console.log(this.columns[i])
                        // }
                         this.column.push(item.name)
                        this.selectedColumn[item.name] = true
                    })
                    this.paymentColumn.forEach(item=>{
                        this.columns[item.name] = true
                         this.column.push(item.name)
                        this.selectedColumn[item.name] = true
                    })
                    console.log(this.column)
                } else {
                    this.tableData = [];
                    this.totalPage = 0;
                    this.$message.error(data.msg);
                }
            });
        },
        sum(list) {
            var sum = 0;
            list.forEach(element => {
                sum += parseFloat(element.paySum)
            });

            return sum;
        },
        paymentSum(list) {
            var sum = 0;
            list.forEach(element => {
                sum += parseFloat(element.paymentSum)
            });

            return sum.toFixed(2);
        },
        columnChange() {
            this.selectedColumn = {}
            this.column.forEach(item=>{
                this.selectedColumn[item] = true
            })
        },
        // 每页数
        sizeChangeHandle(val) {
            this.pageSize = val;
            this.pageIndex = 1;
            this.getDataList();
        },
        // 当前页
        currentChangeHandle(val) {
            this.pageIndex = val;
            this.getDataList();
        },
        tableSum(param) {
            const {columns,data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                sums[index] = '合计';
                return;
                }

                // switch(column.property) {
                //     case "housePrice":
                //     sums[index] = this.tableData[index].housePrice.toFixed(2) + '元';
                //     break;
                //     case "profit":
                //     sums[index] = 666 / 100 + '元';
                //     break;
                //     default:
                //     break;
                // }
                if (column.label == '标准房价') {
                    sums[index] = 0
                    this.tableData.forEach(item=>{
                        sums[index] += item.housePrice
                    })
                }
                if (column.label == '房费') {
                    sums[index] = 0
                    this.tableData.forEach(item=>{
                        sums[index] += item.roomPrice
                    })
                }

                if (column.label == '红冲') {
                    sums[index] = 0
                    this.tableData.forEach(item=>{
                        sums[index] -= item.hc
                    })
                }

                if (column.label == '优惠金额') {
                    sums[index] = 0
                    this.tableData.forEach(item=>{
                        sums[index] -= item.yhje
                    })
                }

                if (column.label == '费用合计') {
                    sums[index] = 0
                    this.tableData.forEach(item=>{
                        item.consumeInfo.forEach(item2=>{
                            sums[index] += parseFloat(item2.paySum)
                        })
                        sums[index] += (item.roomPrice - item.hc)
                    })
                }

                if (column.label == '收款合计') {
                    sums[index] = 0
                    this.tableData.forEach(item=>{
                        item.payment.forEach(item2=>{
                            sums[index] += parseFloat(item2.paymentSum)
                        })
                    })
                    sums[index] = sums[index].toFixed(2)
                }
                this.tableData.forEach(item=>{
                    item.consumeInfo.forEach(item2=>{
                        if (item2.payTypeName == column.label) {
                            if (sums[index]) {
                                sums[index] += parseFloat(item2.paySum)
                            } else {
                                sums[index] = 0
                                sums[index] += parseFloat(item2.paySum)
                            }
                        }
                    })

                    item.payment.forEach(item2=>{
                        if (item2.paymentName == column.label) {
                            if (sums[index]) {
                                sums[index] += parseFloat(item2.paymentSum)
                            } else {
                                sums[index] = 0
                                sums[index] += parseFloat(item2.paymentSum)
                            }
                        }
                    })
                })
            });
            this.loadColumn = true
            return sums;
        },
        exportExcel () {
      /* 从表生成工作簿对象 */

        var fix = document.querySelector('.el-table__fixed');

        console.log('fix:',fix)

        var wb;
        if (fix) {
            wb = XLSX.utils.table_to_book(document.querySelector('#tableData').removeChild(fix));
            document.querySelector('#tableData').appendChild(fix);
        } else {
            wb = XLSX.utils.table_to_book(document.querySelector('#tableData'));
        }

    //   var wb = XLSX.utils.table_to_book(document.querySelector("#tableData"));

      console.log(wb)

      // downloadfn(XLSX.utils.sheet_to_json(wb['Sheets']['Sheet1']), this.config);

      // return

      /* 获取二进制字符串作为输出 */

      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        align: 'center',
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          '营业日报明细表.xlsx'
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    CreateOneFormPage() {
        var fix = document.querySelector('.el-table__fixed');

        console.log('fix:',fix)

        var wb;
        if (fix) {
            wb = XLSX.utils.table_to_book(document.querySelector('#tableData').removeChild(fix));
        } else {
            wb = XLSX.utils.table_to_book(document.querySelector('#tableData'));
        }
        var footer = '<div id="footer" style="width: 100%;text-align: right;margin-top:20px">' +
        '<span style="margin-right: 20px;">打印时间：' +
        Moment(new Date()).format("YYYY-MM-DD HH:mm:ss") +
        '</span>' +
        '<span>打印人：' +
        this.$store.state.user.name +
        '</span>' +
        '</div>';
        $('#tableData').append(footer)
      print({
        printable: 'tableData',
        type: 'html',
        documentTitle:'易信管理平台',
        header: this.seller + '营业日报明细表',
        headerStyle: 'text-align:center;color:#f00!important;width:100%;border:1px #000 solid;',
        // targetStyles: ['border', 'padding: 15px'],
        scanStyles: false,
        style: 'table tr td,th { border-collapse: collapse;padding: 15px;border:1px #000 solid;} td{word-wrap:break-word;word-break:break-all;} table{table-layout：fixed;}' // 表格样式
      })

      document.querySelector('#tableData').appendChild(fix);
      $('#footer').remove()
    }

    },
    mounted() {
        // var column=Object.keys(this.tableData[0])
        // this.column=column
        // column.forEach(item=>{
        //     this.columns[item]=true
        //     this.checkColumn[item]=true
        // })
        this.getDataList();
        this.getleix();
        this.getSellerAndUser();
    }
}
</script>
<style scoped>
    /* .el-checkbox+.el-checkbox {
     margin-left: 0px;
    } */
</style>
